/****************************************************************

this file is part of Music Practice Audio Player
Copyright (C)2012 Serhii Ratsyborynskyi (ratz@live.ru)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

******************************************************************/

#include "MPAFile.hpp"
#include <QIODevice>
#include <QVector>
#include <QDebug>
using namespace AudioCore;




bool MPAFile::encodeMpaFile(const QDir &SourceDir, const QString &TargetFilePath)
{

    QStringList filter;
    filter << "*.mp3";
    QFileInfoList fileList = SourceDir.entryInfoList(filter);
    QByteArray data;

    qDebug() <<"MPA Creation file started";
    // Define file format
    unsigned short Format = 0x0;
    data.append((char *)(&Format), 1);

    // Fill file info size
    if(fileList.size()<255)
    {
        unsigned short fsize = static_cast<unsigned short>(fileList.size());
        data.append((char*)(& fsize) ,1);
    }

    // Fill file infos
    foreach (QFileInfo fileInfo, fileList)
    {
        MPATrackInfo fileInfoStruct;
        const QString & fileName = fileInfo.fileName();
        for(qint32 i = 0; i < 20; i++)
        {
            if(fileName.size()>i)
            {
                fileInfoStruct.name[i] = fileName[i];
            }
            else
            {
                fileInfoStruct.name[i]= ' ';
            }
        }

        fileInfoStruct.trackLength = fileInfo.size();
        qDebug() << sizeof(MPATrackInfo);
        qDebug() << sizeof(fileInfoStruct);
        data.append( (char*) (&fileInfoStruct), sizeof(MPATrackInfo));

    }

    // append reslt file with binary files data
    bool result;
    QFile TargetFile(TargetFilePath);
    if(!TargetFile.exists())
    {
        if(TargetFile.open(QIODevice::WriteOnly))
        {
            result= TargetFile.write(data);
            const qint32 size = 50000;
            char * rdata = new char[size];

            foreach (QFileInfo fileInfo, fileList)
            {
                QFile wavfile(fileInfo.absoluteFilePath());
                if(wavfile.exists())
                {
                    wavfile.open(QIODevice::ReadOnly);
                    while( !wavfile.atEnd())
                    {
                        qint64 wsize = wavfile.read(rdata, size);
                        TargetFile.write(rdata, wsize);
                    }
                    wavfile.close();
                }
                else
                {
                    qDebug() << "WavFile not found" << fileInfo.absoluteFilePath();
                }
            }

            delete rdata;

            TargetFile.close();
        }
    }
    return result;
}

bool MPAFile::decodeMpaFile(const QDir &targetDir, const QString &sourceFile, QStringList & unpackedFileList)
{
    QFile mpaFile(sourceFile);
    unpackedFileList.clear();

    if(! mpaFile.exists() )
    {
        qDebug() << "File does not exists: " << sourceFile;
        return false;
    }

    if( mpaFile.open(QIODevice::ReadOnly) )
    {
        qDebug() << "File cannot be opened: " << sourceFile << " error : " << mpaFile.errorString();
    }

    QList<MPATrackInfo> trackInfoList;

    qint64 readSize;

    unsigned short format = 0;
    unsigned short infoSize = 0;

    MPATrackInfo trackInfo;

    readSize = mpaFile.read((char *) (&format), 1);
    qDebug() << "Read size" << readSize;
    readSize = mpaFile.read((char *) (&infoSize), 1);
    qDebug() << "Read size" << readSize;
    qDebug() << "Found track info: " << infoSize;

    for( unsigned short i = 0; i < infoSize; i++ )
    {
        mpaFile.read((char *) (&trackInfo), sizeof(MPATrackInfo) );
        trackInfoList.push_back(trackInfo);
        QString name( trackInfo.name, 20);
        qDebug() << "Track name:" << name;
        qDebug() << "Track size: " << trackInfo.trackLength;
    }

    foreach (trackInfo, trackInfoList) {
        QString name = targetDir.absolutePath()+"\\"+QString( trackInfo.name, 20).trimmed();

        QByteArray byteArray = mpaFile.read(trackInfo.trackLength);
        QFile mediaFile(name);
        if( mediaFile.exists() )
        {
            mediaFile.remove();
        }
        if( mediaFile.open(QFile::WriteOnly) )
        {
            mediaFile.write(byteArray);
            mediaFile.close();
            unpackedFileList.push_back( name );
        }
        else
        {
            qDebug() << "Failed to open for writing " << name;
        }
    }
    return true;
}

MPAFile::MPAFile()
{
}


